package com.wellgoon.test.exam;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串中出现字母次数
 */
public class HJ2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入小于500个的字母、数字和空格组合的字符");
        while (sc.hasNext()) {
            String first = sc.nextLine();
            if (first.length() > 500) {
                System.err.println("输入超过500字符错误");
                System.out.println("the first string over 500 char error!");
                continue;
            }
            if (!first.matches("^[a-zA-z0-9 ]+$")) {
                System.err.println("输入不符合错误：请输入字母、数字和空格");
                System.out.println("请输入小于500个的字母、数字和空格组合的字符");
                continue;
            }
            System.out.println("请输入一个字母");
            String second = sc.nextLine();
            if (second.length() > 1) {
                System.err.println("输入不符合错误：请输入一个英文字母（不区分大小写）");
                System.out.println("请输入小于500个的字母、数字和空格组合的字符");
                continue;
            }
            if (!second.matches("^[a-zA-Z]")) {
                System.err.println("输入不符合错误：请输入一个英文字母（不区分大小写）");
                System.out.println("请输入小于500个的字母、数字和空格组合的字符");
                continue;
            }
            Pattern p = Pattern.compile(second, Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(first);
            int count = 0;
            while (m.find()) {
                count++;
            }
            System.out.println("第一行字符串中出现有[" + second + "]字母的次数是：" + count);

            /*char[] firstChars = first.toCharArray();
            int num = 0;
            for (int i = 0; i < firstChars.length; i++) {
                if (String.valueOf(firstChars[i]).equalsIgnoreCase(second)) {
                    num++;
                }
            }
            System.out.println(num);*/
        }
    }
}
